package 反射5;
/*
@Date:2025/3/17
*/

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MyJbutils {
    public static <T> List<T> findList(String sql, Class<T> c) throws Exception {
//创建集合存储所有对象数据
        final ArrayList<T> arrayList = new ArrayList<>();
        //注册操作数据的驱动 反射
        Class.forName("com.mysql.cj.jdbc.Driver");
        //使用api链接数据库
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "123456");
//创建Statement
        final Statement statement = conn.createStatement();
        //返回结果集合
        final ResultSet resultSet = statement.executeQuery(sql);
        System.out.println("resultSet = " + resultSet);
//从结果集合获取结果集的元数据
        final ResultSetMetaData metaData = resultSet.getMetaData();
        System.out.println("metaData = " + metaData);
//获取集合中的列数
        final int count = metaData.getColumnCount();
        System.out.println("count = " + count);
        //解析结果集合
        while (resultSet.next()) {
            //动态获取一行数据之后，封装成实体对象
             T t = c.newInstance();
            System.out.println("t = " + t);
            for (int i = 1; i <= count; i++) {
                //通过列的序号获取列值
                Object value = resultSet.getObject(i);
                if (value != null) {
                    //通过列的序号获取列名
                    final String columnName = metaData.getColumnName(i);
                    System.out.println("catalogName = " + columnName);
                    //列名和实体名一致，构造反射
                    Field declaredField = c.getDeclaredField(columnName);
                    //允许访问javabean私有属性
                    declaredField.setAccessible(true);
                    declaredField.set(t, value);


                }

            }
            arrayList.add(t);
        }


        return arrayList;
    }
}
